package com.ht.api.call.func.impl.kf;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.exception.HtException;
import com.ht.api.open.OpenUtil;
import com.ht.api.service.WwxService;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 添加客服账号的前置函数
 * @author asq
 * @createTime 2025年3月9日 09:11:00
 */
public class KfAccountAddFunctionCall implements IFunctionCall {
	/** 接口ID：添加客服账号 */
	private static final long API_ID = 1891359384160833536L;
	/** 接口ID：获取客服账号链接 */
	private static final long API_ID_KF_ADD_CONTACT_WAY = 1891360716645076992L;

	@Override
	public String getName() {
		return "添加客服账号";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 调用企微接口
		String appId = param.getStr("appid");

		// 获取头像的媒体ID
		String imageMediaId = WwxService.getTempImageMediaId(appId, param.getStr("avatar"));

		// 请求平台接口创建账号
		JSONObject accountParam = JSONUtil.createObj();
		accountParam.set("name", param.getStr("name"));
		accountParam.set("media_id", imageMediaId);
		String str = OpenUtil.call(appId, API_ID, accountParam);
		
		// 如果企微接口调用成功，则操作本地数据库
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			String openKfid = obj.getStr("open_kfid");
			String url = getUrl(appId, openKfid);
			param.set("url", url);
			param.set("open_kfid", openKfid);
		} else {
			throw new HtException("企微接口返回错误：" + obj.getStr("errmsg"));
		}
		
		return JSONUtil.createObj();
	}


	/**
	 * 获取客服账号链接
	 * @param appId
	 * @param openKfid
	 * @return
	 */
	private String getUrl(String appId, String openKfid) {
		JSONObject param = JSONUtil.createObj();
		param.set("open_kfid", openKfid);
		param.set("scene", openKfid);
		String str = OpenUtil.call(appId, API_ID_KF_ADD_CONTACT_WAY, param);
		JSONObject result = JSONUtil.parseObj(str);
		if (result.getInt("errcode") == 0) {
			return result.getStr("url");
		}
		return null;
	}



}
